package com.jvm.reentrantlockp;

import java.util.concurrent.locks.ReentrantLock;

// 公平锁与非公平锁测试
public class Demo5 {

    private static int num = 0;

    /**
     *
ReentrantLock 的使用过程：
创建锁：ReentrantLock lock = new ReentrantLock();
获取锁：lock.lock()
释放锁：lock.unlock();
     *
     */
    private static ReentrantLock fairLock = new ReentrantLock(true);// 公平
//    private static ReentrantLock fairLock = new ReentrantLock(false);// 非公平


    public static class T extends Thread {

        public T(String name) {
            super(name);
        }

        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                fairLock.lock();
                try {
                    System.out.println(this.getName() + " 获得锁！");
                } finally {
                    fairLock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T t1 = new T("t1");
        T t2 = new T("t2");
        T t3 = new T("t3");

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

    }

}
